package com.atbeijing.D02;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * filter的使用
 *针对流中的每一个元素选择输出或者不输出
 */
public class Example3 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<SensorReading> source = env.addSource(new SensorSource());

        source.filter(new FilterFunction<SensorReading>() {
            @Override
            public boolean filter(SensorReading sensorReading) throws Exception {
                return sensorReading.id.equals("sensor_1");
            }
        }).print();

        //使用flatMap实现filter
        source.flatMap(new FlatMapFunction<SensorReading, SensorReading>() {
            @Override
            public void flatMap(SensorReading sensorReading, Collector<SensorReading> collector) throws Exception {
                if (sensorReading.id.equals("sensor_1")){
                    collector.collect(sensorReading);
                }
            }
        }).print();


        env.execute();
    }
}
